package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Copyright (C), 2022-2022, 西南科技大学
 * FileName: MsmApiController
 * Author:   swust-liuchuan
 * Date:     2022/7/19 19:46
 * Description: 阿里云短信服务
 * History:
 */

@Api(tags = "短信发送api")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "短信发送")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //先判断redis缓存中是否有验证码
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }

        //如果redis没有验证码,生成4位验证码
        code = RandomUtil.getFourBitRandom();
        //调用service发送方法.判断验证码是否发送成功
        boolean isSend = msmService.sendCode(phone, code);

//        if (isSend) {
//            //发送成功,把值设置到redis缓存中,设置2分钟失效
//            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
//            return Result.ok();
//        } else {
//            throw new YyghException(ResultCodeEnum.SERVICE_ERROR);
//        }
        //发送成功,把值设置到redis缓存中,设置2分钟失效
        System.out.println("验证码: "+code);
        redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
        return Result.ok();
    }
}